package com.jueling.culture.core.service.impl;


import com.jueling.culture.compent.RedisComponent;
import com.jueling.culture.core.service.TokenManageService;
import com.jueling.culture.dto.TokenDto;
import com.jueling.culture.model.UserInfo;
import com.jueling.culture.util.EncryptionUtil;
import com.jueling.culture.util.RandomUtil;
import com.jueling.culture.util.RedisKeyGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author: linp
 * @time: 2019/6/11 17:56
 */
@Service
public class TokenManageServiceImpl implements TokenManageService {

    public static final String ACC_SECRET_KEY = "fjgtLokiLhshOdin";

    public static final String SECRET = "BMSPTV@KeyFJCMCC";

    @Autowired
    private RedisComponent redisComponent;

    private static final Long TOKEN_EXPIRE_TIME=7200L;

    @Override
    public TokenDto createToken(UserInfo userInfo) {
        String randomCode = RandomUtil.getRandomCode();
        String accessToken = EncryptionUtil.aesEncrypt(userInfo.getUserName()+":"+ randomCode, ACC_SECRET_KEY);
        userInfo.setRandom(randomCode);
        UserInfo.currentUser.set(userInfo);
        redisComponent.setObj(RedisKeyGeneratorUtil.accessTokenRedisKeyGenerator(userInfo.getUserName()), userInfo, TOKEN_EXPIRE_TIME);
        return new TokenDto(accessToken);
    }

    @Override
    public void refreshToken(UserInfo userInfo) {
        redisComponent.setObj(RedisKeyGeneratorUtil.accessTokenRedisKeyGenerator(userInfo.getUserName()), userInfo, TOKEN_EXPIRE_TIME);
    }


    /**
     * 根据用户userName删除token
     * @param userName
     */
    @Override
    public void deleteTokenByUserId(String userName) {
        redisComponent.remove(RedisKeyGeneratorUtil.accessTokenRedisKeyGenerator(userName));
    }



}
